package com.deer.wms.base.system.web.check;

import com.deer.wms.base.system.dao.check.BoxItemCheckDetailMapper;
import com.deer.wms.base.system.dao.check.BoxItemCheckMapper;
import com.deer.wms.base.system.dao.ware.ShelfInfoMapper;
import com.deer.wms.base.system.model.bill.MaterialDetail;
import com.deer.wms.base.system.model.box.AreaBoxItem;
import com.deer.wms.base.system.model.box.AreaBoxItemDto;
import com.deer.wms.base.system.model.box.BoxItemCriteria;
import com.deer.wms.base.system.model.box.BoxItemDto;
import com.deer.wms.base.system.model.check.*;
import com.deer.wms.base.system.model.task.RequestBatch;
import com.deer.wms.base.system.model.task.RequestRepertory;
import com.deer.wms.base.system.model.ware.AreaInfo;
import com.deer.wms.base.system.model.ware.ShelfInfo;
import com.deer.wms.base.system.model.zh.ElectricBoxDetail;
import com.deer.wms.base.system.model.zh.WorkTasks;
import com.deer.wms.base.system.service.bill.IMaterialDetailService;
import com.deer.wms.base.system.service.box.AreaBoxItemService;
import com.deer.wms.base.system.service.box.IBoxItemService;
import com.deer.wms.base.system.service.check.BoxItemCheckDetailService;
import com.deer.wms.base.system.service.check.BoxItemCheckService;
import com.deer.wms.base.system.service.ware.IAreaInfoService;
import com.deer.wms.common.annotation.Log;
import com.deer.wms.common.core.controller.BaseController;
import com.deer.wms.common.core.domain.AjaxResult;
import com.deer.wms.common.core.page.TableDataInfo;
import com.deer.wms.common.core.result.CommonCode;
import com.deer.wms.common.core.result.Result;
import com.deer.wms.common.core.result.ResultGenerator;
import com.deer.wms.common.core.text.Convert;
import com.deer.wms.common.enums.BusinessType;
import com.deer.wms.common.utils.DateUtils;
import com.deer.wms.common.utils.poi.ExcelUtil;
import com.deer.wms.framework.util.ShiroUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Condition;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/boxitemcheck")
@Transactional(rollbackFor = Exception.class)
public class BoxItemCheckController extends BaseController {
    @Autowired
    BoxItemCheckDetailMapper boxItemCheckDetailMapper;
    @Autowired
    private IAreaInfoService areaInfoService;
    @Autowired
    private AreaBoxItemService areaBoxItemService;
    @Autowired
    private BoxItemCheckService boxItemCheckService;
    @Autowired
    private BoxItemCheckDetailService boxItemCheckDetailService;
    @Autowired
    BoxItemCheckMapper boxItemCheckMapper;
    @Autowired
    ShelfInfoMapper shelfInfoMapper;
    @Autowired
    IBoxItemService iBoxItemService;
    @Autowired
    IMaterialDetailService iMaterialDetailService;

    String prefix = "check";

    @RequestMapping("check")
    public String check() {
        return prefix + "/check";
    }

    @RequestMapping("add")
    public String add() {
        return prefix + "/add";
    }

    @RequestMapping("detail")
    public String detail() {
        return prefix + "/detail";
    }
    @RequestMapping("list")
    public String list() {
        return prefix + "/list";
    }


    /*盘点列表*/
    @PostMapping("/findList")
    @ResponseBody
    public TableDataInfo findList(BoxItemCheck boxItemCheck) {
        startPage();
        List<BoxItemCheck> all = boxItemCheckService.selectall(boxItemCheck);
        return getDataTable(all);
    }

    /*手持机盘点列表*/
    @PostMapping("/pdaFindList")
    @ResponseBody
    public List<BoxItemCheck> pdaFindList(BoxItemCheck boxItemCheck) {
        return boxItemCheckService.selectallPda(boxItemCheck);
    }

    /*创建盘点单*/
    @PostMapping("/getCheck")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult getCheck(String id) {
        String createUserName = ShiroUtils.getLoginName();
        //盘点单号
        SimpleDateFormat date = new SimpleDateFormat("yyyyMMdd-HHmmss");
        String PdCode = "PD"+date.format(new Date());
        //新建盘点单
        BoxItemCheck boxItemCheck = new BoxItemCheck();
        boxItemCheck.setCreateUserName(createUserName)
                .setBillNo(PdCode);
        boxItemCheckService.insertBoxItemCheck(boxItemCheck);

        //添加盘点明细
        BoxItemCheckDetail boxItemCheckDetail;
        String[] strings = Convert.toStrArray(id);
        int re = 0;
        for (String ids : strings) {
            //根据托盘id查询对应明细 dto
            boxItemCheckDetail = boxItemCheckService.findCheckDetailById(Integer.parseInt(ids));
            boxItemCheckDetail.setState(1)//1未盘
                    .setBoxItemCheckId(boxItemCheck.getBoxItemCheckId());//id
            //创建盘点明细
            re = boxItemCheckService.blockedBoxItem(boxItemCheckDetail);
        }

        return toAjax(re);
    }

    /*盘点明细*/
    @PostMapping("/findListdetail")
    @ResponseBody
    public TableDataInfo findListdetail(@RequestParam Integer id) {
        startPage();
        BoxItemCheckDetail b = new BoxItemCheckDetail();
        b.setBoxItemCheckId(id);
        List<BoxItemCheckDetail> select = boxItemCheckDetailService.selectbyid(id);
        return getDataTable(select);
    }
    /*盘点托盘明细*/
    @PostMapping("/findBoxItemCheckDetailList")
    @ResponseBody
    public List<BoxItemCheckDetailDto> findBoxItemCheckDetailList(@RequestParam Integer id) {
        List<BoxItemCheckDetailDto> list =  boxItemCheckDetailService.findBoxItemCheckDetailList(id);
        return list;
    }

    /*盘点明细列表*/
    @PostMapping("/findListdetailBox")
    @ResponseBody
    public TableDataInfo findListdetailBox(BoxItemCheckDetailDto boxItemCheckDetailDto) {
        startPage();
        List<BoxItemCheckDetailDto> select = boxItemCheckDetailService.findListdetailBox(boxItemCheckDetailDto);
        return getDataTable(select);
    }

    /*手持扫码盘点*/
    @PostMapping("/sendBillInDetail")
    @ResponseBody
    @Transactional
    public Result sendBillInDetail(String json){
        List<WorkTasks> workTaskList = new Gson().fromJson(json, new TypeToken<List<WorkTasks>>(){}.getType());
        //获取查询盘点托盘的盘点单id和批号
        WorkTasks workTask = new WorkTasks();
        String boxMsg = workTaskList.get(0).getMsg();
        String[] batchMsg = boxMsg.split(",");
        workTask.setBatch(batchMsg[4]); //批号
        workTask.setBoxItemCheckId(workTaskList.get(0).getBoxItemCheckId());//单id
        List<BoxItemCheckDetail> checkDetalList = boxItemCheckService.findCheckDetalBybatch(workTask);
        if(checkDetalList.size() == 0){
            return ResultGenerator.genFailResult(CommonCode.MATERIAL_DUP);
        }

        //获取明细id
        BoxItemCheckDetail boxItemCheckDetail = checkDetalList.get(0);

        String strMsg = ""; //条码
        Float weight = 0f;//重量
        for (WorkTasks workTasks : workTaskList) {
            strMsg = workTasks.getMsg();
            String[] msg = strMsg.split(",");
            Float msg3 = Float.parseFloat(msg[3].replaceAll("[a-zA-Z]", ""));
            weight = msg3 + weight;
        }
        //添加盘点信息
        boxItemCheckDetail.setCheckUserName(workTaskList.get(0).getCreateUserName())
                .setDiffWeight(weight-boxItemCheckDetail.getWeight())//差额
                .setRealWeight(weight);//盘点重量
        boxItemCheckService.updateCheck(boxItemCheckDetail);

        return ResultGenerator.genFailResult(CommonCode.NUMBER_SUCCESS);
    }

    /*判断库位是否已经盘点*/
    @PostMapping("/checkOver")
    @ResponseBody
    @Transactional
    public Result carriageResult(@RequestBody RequestBatch requestBatch){
        if(requestBatch==null){
            return ResultGenerator.genFailResult(CommonCode.BOXCHECK_ERROR);
        }
        //盘点单为盘点中的
        BoxItemCheckDetail checkState = boxItemCheckService.selectCheckState(requestBatch.getItemcode());
        //盘点明细为已盘点
        if(checkState.getState() != 2){
            return ResultGenerator.genFailResult(CommonCode.BOXCHECK_ERROR);
        }
        int sum = boxItemCheckService.findCheckOverSum(checkState.getBoxItemCheckId());
        if (sum == 0) {
            boxItemCheckService.updateCheckDetailOver(checkState.getBoxItemCheckId());
        }
        return ResultGenerator.genFailResult(CommonCode.WS_SUCCESS);
    }




    /**
     * 导出列表
     */
    //@RequiresPermissions("electricBox:export")
    @PostMapping("/exportlist")
    @ResponseBody
    public AjaxResult exportlist(@RequestParam Integer boxItemCheckId) {
     /*   List<BoxItemDto> list=new ArrayList<>();
        List<BoxItemCheckDetail> selectbyid = boxItemCheckDetailService.selectbyid(boxItemCheckId);
        for (BoxItemCheckDetail b:selectbyid
             ) {
            BoxItemCriteria boxItemCriteria=new BoxItemCriteria();
            boxItemCriteria.setItemCode(b.getMaterialid());
            List<BoxItemDto> boxItemDtos = iBoxItemService.selectBoxItemDtoList(boxItemCriteria);
            System.out.println(boxItemDtos);
            list.addAll(boxItemDtos);
        }*/
        BoxItemCheckDetail b = new BoxItemCheckDetail();
        b.setBoxItemCheckId(boxItemCheckId);
        List<BoxItemCheckDetail> select = boxItemCheckDetailMapper.select(b);

        //System.out.println(list);
        ExcelUtil<BoxItemCheckDetail> util = new ExcelUtil<BoxItemCheckDetail>(BoxItemCheckDetail.class);
        return util.exportExcel(select, "盘点");
    }



    /**
     * 导出列表
     */
    @RequiresPermissions("electricBox:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(ElectricBoxDetail e) {
        List<BoxItemCheck> all = boxItemCheckService.findAll();
        System.out.println(all);
        ExcelUtil<BoxItemCheck> util = new ExcelUtil<BoxItemCheck>(BoxItemCheck.class);
        return util.exportExcel(all, "盘点");
    }

    /**
     * 导出列表
     */
    //@RequiresPermissions("electricBox:partExcel")
    @PostMapping("/partExcel")
    @ResponseBody
    public AjaxResult partExcel(@RequestParam Integer id) {
        List<BoxItemCheckDetailDto> list =  boxItemCheckDetailService.findBoxItemCheckDetailList(id);

        ExcelUtil<BoxItemCheckDetailDto> util = new ExcelUtil<BoxItemCheckDetailDto>(BoxItemCheckDetailDto.class);
        return util.exportExcel(list, "原料区库存盘点单");
    }
    @PostMapping("/findListcheck")
    @ResponseBody
    public BoxItemCheck findListcheck(@RequestParam Integer id) {
        startPage();
        BoxItemCheck byId = boxItemCheckService.findById(id);
        return byId;
    }


}
